package org.infinitest.swingui;

import javax.swing.*;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author <a href="mailto:benrady@gmail.com"Ben Rady</a>
 */
class TreeModelExpansionListener
{
  public static void watchTree(final JTree tree)
  {
    tree.expandPath(tree.getPathForRow(0));
    TreeModelListener listener = (TreeModelListener) Proxy.newProxyInstance(tree.getClass().getClassLoader(), new Class[]{TreeModelListener.class}, new InvocationHandler()
    {
      public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable
      {
        if (method.getName().equals("equals"))
          return TreeModelExpansionListener.class.equals(args[0]);
        if (method.getName().equals("hashCode"))
          return TreeModelExpansionListener.class.hashCode();
        TreeModelEvent e = (TreeModelEvent) args[0];
        expandTreeNodes(tree, e);
        return null;
      }
    });
    tree.getModel().addTreeModelListener(listener);
  }

  private static void expandTreeNodes(JTree tree, TreeModelEvent e)
  {
    for (int i = 0; i < tree.getRowCount(); i++)
    {
      tree.expandRow(i);
    }
  }

}
